using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics.Management;

namespace AzureFiddlerCore.Demo
{
    public class WebRole : RoleEntryPoint
    {
        public static System.Text.StringBuilder _errorLog = new System.Text.StringBuilder();

        public override bool OnStart()
        {
            try
            {
                DiagnosticMonitorTraceListener tmpListener = new DiagnosticMonitorTraceListener();
                System.Diagnostics.Trace.Listeners.Add(tmpListener);                
                
                string wadConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(wadConnectionString));                

                RoleInstanceDiagnosticManager roleInstanceDiagnosticManager = storageAccount.CreateRoleInstanceDiagnosticManager(RoleEnvironment.DeploymentId, RoleEnvironment.CurrentRoleInstance.Role.Name, RoleEnvironment.CurrentRoleInstance.Id);
                DiagnosticMonitorConfiguration config = roleInstanceDiagnosticManager.GetCurrentConfiguration();

                // should never be null, but this is a fallback in case it is. I recommend removing this in a production
                // deployment
                if (null == config)
                {
                    config = DiagnosticMonitor.GetDefaultInitialConfiguration();
                }

                config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
                config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;

                config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Warning;
                config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
               
                roleInstanceDiagnosticManager.SetCurrentConfiguration(config);
                System.Diagnostics.Trace.TraceInformation("Diagnostics Running");                

            }
            catch (Exception ex)
            {
                _errorLog.AppendLine(ex.ToString());
                System.Diagnostics.Trace.TraceError("Error in OnStart: " + ex.Message);
                System.Diagnostics.Trace.TraceError(ex.ToString());
            }

            return base.OnStart();
        }

        public override void OnStop()
        {

            AzureFiddlerCoreLib.AzureFiddlerCore.Shutdown();
            
            base.OnStop();
        }
    }
}
